import schedule from 'node-schedule'
let jobs = {}

class Timer {
  /*******
   * @description:
   * @param {*} name 定时任务名字
   * @param {*} cron corn表达式 具体如何表达请参考官网
   * @param {*} fuc 调用的方法
   * @return {*}
   * @use:
   */
  SetTimeTask (name, cron, fuc) {
    this.CancelTimeTask(name)
    jobs[name] = schedule.scheduleJob(name, cron, async () => {
      try {
        fuc()
      } catch (error) {
        console.log(error)
      }
    })
  }

  CancelTimeTask (name) {
    if (jobs[name]) {
      jobs[name].cancel()
      delete jobs[name]
    }
  }

  get allTimeTask () {
    return schedule.scheduledJobs
  }

  get allTimeTaskName () {
    return Object.keys(schedule.scheduledJobs)
  }

  CancelAllTimeTask () {
    this.allTimeTaskName.forEach((item) => {
      this.CancelTimeTask(item)
    })
  }

  async sleep (ms) {
    return new Promise((resolve) => setTimeout(resolve, ms))
  }
}

export default new Timer()
